package com.lg.shiro;

import java.io.Serializable;

import org.apache.shiro.session.Session;
import org.apache.shiro.session.mgt.eis.CachingSessionDAO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.util.SerializationUtils;
import org.springframework.util.StringUtils;

import com.lg.redis.simple.RedisClient;

import redis.clients.jedis.Jedis;

@Repository
public class CustomSessionDao extends CachingSessionDAO {
    @Autowired
	private RedisClient redisClient;
    
    private static final String SESSIONPREFIX ="shiro:session:";
	@Override
	protected void doUpdate(Session session) {
		// TODO Auto-generated method stub
		saveSession(session);
	}

	@Override
	protected void doDelete(Session session) {
		// TODO Auto-generated method stub
		if(session == null ||StringUtils.isEmpty(session.getId())) {
			return  ;
		}
		Jedis jedis = redisClient.getJedis();
		try {
			Serializable id = session.getId();
			String rediskey = (SESSIONPREFIX + id);
			jedis.del(rediskey);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally {
			jedis.close();
		}
	}

	@Override
	protected Serializable doCreate(Session session) {
		Serializable sessionId = generateSessionId(session);
		assignSessionId(session, sessionId);
		saveSession(session);
		return sessionId;
	}

	public void saveSession(Session session) {
		if(session == null ||session.getId()==null ) {
			return  ;
		}
		Jedis jedis = redisClient.getJedis();
		try {
			Serializable id = session.getId();
			String rediskey = (SESSIONPREFIX + id);
			byte[] rediskey1 = rediskey.getBytes();
			byte[] value = SerializationUtils.serialize(session);
			jedis.set(rediskey1, value);
			jedis.expire(rediskey1, 600);
		} finally {
			jedis.close();
		}
	}
	@Override
	protected Session doReadSession(Serializable sessionId) {
		// TODO Auto-generated method stub
		if(sessionId==null || StringUtils.isEmpty(sessionId))
		return null;
		Jedis jedis = redisClient.getJedis();
		try {
			String rediskey = (SESSIONPREFIX + sessionId.toString());
			byte[] rediskey1 = rediskey.getBytes();
			byte[] bs = jedis.get(rediskey1);
			Session session = (Session) SerializationUtils.deserialize(bs);
			return session;
		} finally {
			jedis.close();
		}
	}

}
